package net.didactylos.helpline.servlet;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.hibernate.Session;

import net.didactylos.helpline.data.Conversation;
import net.didactylos.helpline.data.User;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.RedirectResolution;

public class SessionListener implements HttpSessionListener
{

	public void sessionCreated(HttpSessionEvent sessionEvent)
	{
		// Does nothing.
	}

	public void sessionDestroyed(HttpSessionEvent sessionEvent)
	{
		User user = (User) sessionEvent.getSession().getAttribute("user");
		
		// Release owned conversation
		if (user != null)
		{
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			
			Conversation conversation = (Conversation) session
			.createQuery("from Conversation as conv where conv.owner = ?")
			.setParameter(0, user)
			.uniqueResult();
			
			if (conversation != null)
			{
				conversation.setOwner(null);
				session.update(conversation);
			}
			
			session.getTransaction().commit();
			if (session.isOpen())
			{
				session.close();
			}
		}
		
	}

}
